﻿using System.Net.Mail;
using System.Net;
using System.Text;

namespace AutoMail.Email
{
    public class EmailHelper : IEmailHelper
    {
        /// <summary>
        /// 邮件服务器
        /// </summary>
        private string smtpServer = @"smtp.163.com";
        //发送账户账号

        private string mailAccount = @"13272143617@163.com";
        //发送账户密码
        private string pwd = @"CBXEAODWCAMERKQX";

        private SmtpClient _smtpClient { get; set; }

        public EmailHelper()
        {
            init(this.mailAccount, this.pwd);
        }

        public EmailHelper(string account, string password)
        {
            init(account, password);
        }

        private void init(string account, string password)
        {
            _smtpClient= new SmtpClient();
            _smtpClient.Host = smtpServer;
            _smtpClient.Port = 25;
            _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//默认network
            _smtpClient.EnableSsl = true;
            //smtpClient.UseDefaultCredentials = true; //打开这个会报错，无法发送邮件
            _smtpClient.Credentials = new NetworkCredential(account, password);
        }
        public void SetSmtpServer(string server)
        {
            this.smtpServer = server;
        }

        public void SetAccount(string account, string pwd)
        {
            this.mailAccount = account;
            this.pwd = pwd;
            _smtpClient.Credentials = new NetworkCredential(mailAccount, pwd);
        }

        public async Task SendEmail(EmailContextDto par)
        {
            MailMessage mailMessage = new MailMessage(mailAccount, par.reciver);
            mailMessage.Subject = par.Title;
            mailMessage.Body = par.Context;
            mailMessage.BodyEncoding = Encoding.UTF8;
            mailMessage.IsBodyHtml = false;
            mailMessage.Priority = MailPriority.Normal;
            await _smtpClient.SendMailAsync(mailMessage);
        }

        public async Task SendEmail(List<EmailContextDto> par)
        {
            par.ForEach(async x =>
            {
                MailMessage mailMessage = new MailMessage(mailAccount, x.reciver);
                mailMessage.Subject = x.Title;
                mailMessage.Body = x.Context;
                mailMessage.BodyEncoding = Encoding.UTF8;
                mailMessage.IsBodyHtml = false;
                mailMessage.Priority = MailPriority.Normal;
                await _smtpClient.SendMailAsync(mailMessage);
            });
            await Task.CompletedTask;
        }
    }
}